using System.Collections.Generic;
using NHibernate;

namespace DataLayer.Repositories
{
    public abstract class BaseRepository<TEntity, TPk> : IRepository<TEntity, TPk>
        where TEntity : class
    {
        private readonly ISession _session;


        protected BaseRepository(ISession session)
        {
            _session = session;
        }

        public ISession Session
        {
            get { return _session; }
        }

        #region IRepository<TEntity,TPk> Members

        public TEntity GetById(TPk id)
        {
            return Session.Get<TEntity>(id);
        }

        public IList<TEntity> GetAll()
        {
            return Session.CreateCriteria(typeof (TEntity)).List<TEntity>();
        }

        public virtual TEntity Add(TEntity entity)
        {
            using (ITransaction transaction = Session.BeginTransaction())
            {
                Session.Save(entity);

                transaction.Commit();
            }
            return entity;
        }

        public TEntity Update(TEntity entity)
        {
            using (ITransaction transaction = Session.BeginTransaction())
            {
                entity = (TEntity) Session.Merge(entity);
                transaction.Commit();
            }

            return entity;
        }

        #endregion

        public virtual ICriteria CreateCriteria()
        {
            return Session.CreateCriteria<TEntity>();
        }
    }
}